<template>
  <el-dialog
    v-bind="$attrs"
    :modal='false'
    :show-close='false'
    top='20px'
    width="700px"
    append-to-body>
    <div slot="title" class="dialog-header">
      <el-col :span="16">
        <h4>{{ title }}</h4>
      </el-col>
      <el-col :span="8" style="text-align: right;">
        <el-button type="info" @click="$emit('update:visible', false)">关闭</el-button>
      </el-col>
    </div>
    <el-row :gutter="20" style="height: calc(100vh - 250px);overflow: auto;">
      <el-form label-position="left" label-width="80px" :model="post_form" :rules="rules" ref="post_form">
        <el-col :span="24">
          <el-form-item label="名称" prop="plan_name">
            <el-input v-model="post_form.plan_name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="comment">
            <el-input v-model="post_form.comment" type="textarea"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-input placeholder="模糊筛选的测试用例名称" v-model="scree_key" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="fetchData"></el-button>
          </el-input>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button type="warning" @click="enterCase">加入用例</el-button>
        </el-col>
        <el-col :span="24" style="margin-top: 10px;">
          <el-table
            :data="tableData"
            v-loading='loading_case'
            @selection-change="handleSelectionChange"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            style="width: 100%">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <template v-for="item in table_header">
              <!-- 动态判断是否显示该列 -->
              <template v-if="show_header_fields.includes(item['key'])">
                <el-table-column
                  show-overflow-tooltip
                  align="center"
                  :width="item['width']"
                  :key="item['key']"
                  :label="item['label']"
                  :prop="item['prop']"
                  :column-key="item['columnKey']"
                  :filters="item['filters']"
                  :filter-method="filterHandler"
                  v-if="Object.prototype.hasOwnProperty.call(item, 'filters')">
                <!-- 判断调用筛选列功能 -->
                </el-table-column>
                <el-table-column
                  show-overflow-tooltip
                  align="center"
                  :width="item['width']"
                  :key="item['key']"
                  :label="item['label']"
                  :prop="item['prop']"
                  :column-key="item['columnKey']"
                  v-else
                ></el-table-column>
              </template>
            </template>
          </el-table>
        </el-col>
        <el-col :span="24" style="margin-top: 30px;">
          <el-table
            :data="post_form.test_case"
            :key="itemKey"
            v-loading='loading_plan'
            @selection-change="handleSelectionChange"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            style="width: 100%">
            <template v-for="item in table_header">
              <el-table-column
                show-overflow-tooltip
                align="center"
                :width="item['width']"
                :key="item['key']"
                :label="item['label']"
                :prop="item['prop']"
                :column-key="item['columnKey']"
                :filters="item['filters']"
                v-if="show_header_fields.includes(item['key'])"
              ></el-table-column>
            </template>
            <el-table-column
              fixed="right"
              label="操作"
              width="120">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="deleteRow(scope.$index, post_form.test_case)"
                  type="text"
                  size="small">
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="onSubmit" v-if="title == '新建计划'">提交</el-button>
      <el-button type="primary" @click="editPlan" v-else>修改</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { table_header, show_header_fields } from "./content.data"
import { getTestCase } from "@/api/test_case"
import { addTestPlan, editTestPlan, testExecuteList, delTestExecute } from "@/api/testPlan"

export default {
  props: {
    post_form: {},
    title: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      rules: {
        plan_name: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
      },
      loading_case: false,
      table_header,
      show_header_fields,
      scree_key: '',
      // 测试用例
      tableData: [],
      // 确认加入测试计划的用例
      multipleSelection: [],
      loading_plan: false,
      // 用来强制刷新table
      itemKey: '',
    }
  },
  watch: {
    post_form: function (newVal) {
      // TODO: 清空之前可能存在的勾选
      // 获取测试计划对应的测试执行
      if (this.title == '编辑计划') {
        this.loading_plan = true
        testExecuteList({'id': newVal.id}).then(res => {
          this.post_form['test_case'] = []
          for(var i = 0, len = res.data.length; i < len; i++) {
            // 插入execute_id, 以此识别编辑计划状态下, 那条是新增的数据
            res.data[i].test_case['execute_id'] = res.data[i].id
            this.post_form['test_case'].push(res.data[i].test_case)
          }
          this.itemKey = Math.random()
          this.loading_plan = false
        }, err => {
          this.loading_plan = false
        }) 
      }
    }
  },
  methods: {
    // 获取初始数据
    fetchData() {
      this.loading_case = true
      getTestCase({'title': this.scree_key}).then(res => {
        this.loading_case = false
        this.tableData = res.data
      }, err => {
        this.loading_case = false
      })
    },
    // 新增计划
    onSubmit() {
      this.$refs['post_form'].validate((valid) => {
        if (valid) {
          addTestPlan(this.post_form).then(res => {
            // 清除表单验证
            this.$nextTick(()=>{
              this.clearFormValidate()
            })
            this.$emit('update:visible', false)
            this.$emit('fetchData')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 编辑测试计划
    editPlan() {
      this.$refs['post_form'].validate((valid) => {
        if (valid) {
          editTestPlan(this.post_form).then(res => {
            this.$emit('fetchData')
            this.$emit('update:visible', false)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 清除验证
    clearFormValidate() {
      this.$refs['post_form'].clearValidate()
    },
    // 表头筛选
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    // 多选table表 - 选中后
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 确认加入计划
    enterCase() {
      this.post_form['test_case'].push(...this.multipleSelection)
      this.itemKey = Math.random()
    },
    // 已加入计划的用例table表 - 删除
    deleteRow(index, table) {
      if (Object.prototype.hasOwnProperty.call(table[index], 'execute_id')) {
        delTestExecute({'execute_id': table[index]['execute_id']}).then(res => {
          table.splice(index, 1)
        })
      } else {
        table.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      }
    },
  },
  mounted() {
    this.fetchData()
  },
}
</script>


<style scoped lang="scss">

</style>

